import { Router } from 'express';
import { db } from '../services/db';
import { IPagedInfo } from '../models/info-res';

export const businessRouter: Router = Router();


businessRouter.get("/Info", async (req, res, next): Promise<any> => {
    const pageNumber = parseInt(<string>req.query.pageNumber);
    const pageSize = parseInt(<string>req.query.pageSize);
    const query = `${pageNumber}-${pageSize}`;
    let cached = await db.infoRess.findOne({ query });
    if (cached != null)
        return res.json(cached.data);
    let totalCount = await db.infos.estimatedDocumentCount();
    let totalPage = Math.ceil(totalCount * 1.0 / pageSize);
    let infos = await db.infos.find({}, { skip: (pageNumber - 1) * pageSize, limit: pageSize }).toArray();
    let result: IPagedInfo = {
        pageNumber, pageSize, totalCount, totalPage,
        data: infos,
    }
    return res.status(200).json(result);
});

businessRouter.get("/GdpData", async (req, res, next): Promise<any> => {
    const yearStart = parseInt(<string>req.query.yearStart);
    const yearEnd = parseInt(<string>req.query.yearEnd);
    const query = `${yearStart}-${yearEnd}`;
    let cached = await db.gdpRes.findOne({ query });
    if (cached != null)
        return res.json(cached.data);
    let data = await db.gdps.find({ year: { $gte: yearStart, $lte: yearEnd } }).toArray();
    return res.status(200).json(data);
});